const express = require('express');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

const app = express();

// 中间件
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ extended: true, limit: '50mb' }));

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = 'uploads';
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

// 模拟用户数据
const users = {
  admin: {
    id: 1,
    username: 'admin',
    password: 'Admin123',
    real_name: '系统管理员',
    role: 3,
    department: '信息科',
    title: '系统管理员'
  }
};

// 模拟JWT
const createToken = (user) => {
  return 'mock_token_' + user.id + '_' + Date.now();
};

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: 'API运行正常',
    data: {
      timestamp: new Date().toISOString()
    }
  });
});

// 登录
app.post('/api/doctors/login', (req, res) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res.status(400).json({
      success: false,
      message: '用户名和密码不能为空'
    });
  }

  const user = users[username];
  if (!user || user.password !== password) {
    return res.status(401).json({
      success: false,
      message: '用户名或密码错误'
    });
  }

  const token = createToken(user);
  res.json({
    success: true,
    message: '登录成功',
    data: {
      token,
      doctor: {
        doctor_id: user.id,
        username: user.username,
        real_name: user.real_name,
        role: user.role,
        department: user.department,
        title: user.title,
        role_name: user.role === 3 ? '系统管理员' : '医生'
      }
    }
  });
});

// 任务提交
let taskIdCounter = 1;
const taskResults = new Map();

app.post('/api/scoring/submit', upload.single('image'), async (req, res) => {
  try {
    const { patient_code, clinical_text } = req.body;
    const imageFile = req.file;

    console.log('收到任务提交请求:', {
      patient_code,
      clinical_text: clinical_text?.substring(0, 100),
      hasImage: !!imageFile
    });

    // 参数验证
    if (!imageFile) {
      return res.status(400).json({
        success: false,
        message: '请上传内镜图像'
      });
    }

    if (!patient_code || !patient_code.trim()) {
      return res.status(400).json({
        success: false,
        message: '患者编号不能为空'
      });
    }

    const taskId = taskIdCounter++;

    // 模拟AI分析结果
    const mockResult = {
      task_id: taskId,
      patient_code,
      status: 3, // 已完成
      ai_result: {
        score: Math.floor(Math.random() * 13),
        severity_name: ['缓解期', '轻度', '中度', '重度'][Math.floor(Math.random() * 4)],
        severity_code: Math.floor(Math.random() * 4) + 1,
        confidence: Math.floor(Math.random() * 20) + 80,
        analysis_details: '模拟AI分析结果',
        model_version: '1.0.0',
        processing_time_ms: Math.floor(Math.random() * 1000) + 500,
        note: "使用模拟评分模型"
      },
      created_at: new Date().toISOString(),
      completed_at: new Date().toISOString()
    };

    // 保存任务结果
    taskResults.set(taskId, mockResult);

    console.log(`任务 ${taskId} 提交成功`);

    res.json({
      success: true,
      message: 'AI分析完成',
      data: mockResult
    });

    // 清理临时文件
    try {
      fs.unlinkSync(imageFile.path);
      console.log('清理临时文件:', imageFile.path);
    } catch (cleanupError) {
      console.warn('清理临时文件失败:', cleanupError.message);
    }

  } catch (error) {
    console.error('任务提交失败:', error);
    
    // 清理临时文件
    if (req.file) {
      try {
        fs.unlinkSync(req.file.path);
      } catch (cleanupError) {
        console.warn('清理临时文件失败:', cleanupError.message);
      }
    }

    res.status(500).json({
      success: false,
      message: '任务提交失败: ' + error.message
    });
  }
});

// 任务结果查询
app.post('/api/scoring/result', (req, res) => {
  const { task_id } = req.body;

  console.log('查询任务结果:', task_id);

  let result = taskResults.get(task_id);

  if (!result) {
    return res.status(404).json({
      success: false,
      message: '任务不存在',
      data: null
    });
  }

  res.json({
    success: true,
    message: '获取任务结果成功',
    data: result
  });
});

// 任务列表
app.post('/api/scoring/list', (req, res) => {
  const { page = 1, limit = 10, status = null } = req.body;

  const mockTasks = Array.from(taskResults.values()).slice(0, 5);
  const statusNames = { 1: '待处理', 2: '分析中', 3: '已完成', 4: '失败' };

  res.json({
    success: true,
    message: '获取任务列表成功',
    data: {
      items: mockTasks,
      pagination: {
        current_page: parseInt(page),
        page_size: parseInt(limit),
        total: mockTasks.length,
        total_pages: Math.ceil(mockTasks.length / limit)
      }
    }
  });
});

// 启动服务器
const PORT = 4000;
app.listen(PORT, () => {
  console.log(`🚀 修复版服务器启动成功! 端口: ${PORT}`);
  console.log(`📝 测试账号: admin / Admin123`);
  console.log(`📁 文件上传目录: uploads/`);
  console.log(`✅ /api/scoring/result 端点已修复`);
});
